//
//  SinaAccountViewModel.swift
//  weibo
//
//  Created by sirius on 16/1/4.
//  Copyright © 2016年 sirius. All rights reserved.
//

import UIKit
import AFNetworking

class SinaAccountViewModel: NSObject {

    //单例
    static var shareInstance: SinaAccountViewModel = SinaAccountViewModel()
    //创建一个model属性
    var model:SinaAccountModel?
    /*
    model取值 有两种情况
    第一种 根据授权，给其赋值
    第二种直接从沙盒去
    */
    var isLogin :Bool {
        return (SinaAccountViewModel.shareInstance.access_token == "") ? false :true
    }
    var access_token: String {
        return model?.access_token ?? ""
    }
    //在viewModel构造函数中，给model 赋值
    override init() {
        model = SinaAccountModel.readuserInfo()
    }

//MARK:-- 获取网络请求，来获取Token
 func getToken(code: String,success: ()->(),failure: (error: NSError)->()){
    //1.1 建一个实例
    let afn = AFHTTPSessionManager()
    //1.1.1
    afn.responseSerializer.acceptableContentTypes?.insert("text/plain")
    //1.2 拼接参数
    
    let param = [
        "client_id":app_key,
        "client_secret":app_secret,
        "grant_type":"authorization_code",
        "code":code,
        "redirect_uri":redirect_url
        
        
    ]
    //1.2 发送数据请求
    afn.POST("https://api.weibo.com/oauth2/access_token", parameters: param, success: { ( _, JSON) -> Void in
        printLog(JSON)
        let dict = JSON as? [String:AnyObject]
        if let dict = dict {
            let account = SinaAccountModel(dict: dict)
            //获取Token后，进行获取个人信息的请求
//            let myself: SinaOauthViewController = SinaOauthViewController()
            self.getPersonalInfo(account, success: success, failure: failure)
        }
        }) { ( _, error) -> Void in
            printLog(error)
            failure(error: error)
    }
}

//MARK:--获取用户信息
//参数uid与screen_name二者必选其一，且只能选其一；
func getPersonalInfo(accessModel: SinaAccountModel,success: ()->(),failure: (error:NSError)->()) {
    if accessModel.access_token == nil || accessModel.uid == nil{
        fatalError("必须有 用户accesstoken,还有 uid")
    }
    //创建AFN实例
    let afn = AFHTTPSessionManager()
    //2. 拼接参数
    let params = ["access_token":accessModel.access_token!,
        "uid":accessModel.uid!
    ]
    //发送网络请求
    //String? 对于 AnyObject?不能转换，需要强制解包
    afn.GET("https://api.weibo.com/2/users/show.json", parameters: params, success: { (_ , JSON) -> Void in
        printLog(JSON)
        if let dic = JSON as? [String:AnyObject]{
            accessModel.screen_name = dic["screen_name"] as? String
            accessModel.screen_name = dic["profile_image_url"] as? String
            
            self.model = accessModel
            //MARK:---保存用户信息
            accessModel.saveInfo()
            //进行回调，查看成功的结果
//MARK:---给ViewModel中的model 属性赋值
            success()
        }
        }) { (_, error) -> Void in
            failure(error: error)
    }
}
}